/**
 * 用户购买记录查询
 *
 * @format
 */

import  dayjs from 'dayjs'
import { dateFormatter, transformBeijingDate, TBAPIS } from '../../sdk'
import { getSellerSession } from './getSession'
import { TAOBAO_ORDER_STATUS, TAOBAO_SUCCESS_ORDER_STATUS } from '../../constants'

export const getUserOrderlist = async (context, queryStartTime, queryEndTime?, session?: string) => {
  try {
    let results = []
    let currentTime = Date.now()
    // 开始时间以Math.max(当前时间倒推3个月，queryStartTime)
    let lastUpdateTime = dayjs().add(-3, 'month').valueOf()
    console.log(`lastUpdateTime`, lastUpdateTime)
    // 若倒推的3个月时间小于传入的查询开始时间, 则以查询开始时间作为最后更新时间
    if (lastUpdateTime < queryStartTime) {
      lastUpdateTime = queryStartTime
    }
    if (!session) {
      session = (await getSellerSession(context)).session
    }
    // 获取用户在lastUpdateTime ~ currentTime区间的购买情况
    let pageNo = 1
    let pageSize = 100
    let has_next = true
    while (has_next === true) {
      let params = {
        startTime: dateFormatter(new Date(lastUpdateTime)),
        endTime: dateFormatter(new Date(queryEndTime || currentTime)),
        openId: context.openId,
        pageNo,
        pageSize,
        session
      }
      let orderResult = await TBAPIS.getBuyerOrderList(context, params)
      has_next = orderResult.has_next
      if (orderResult.total_results > 0) {
        const { trade } = orderResult.trades
        trade.forEach(i => {
          // 普通下单
          if (TAOBAO_ORDER_STATUS.includes(i.status)) {
            i?.orders?.order?.forEach(s => {
              results.push({
                payTime: i.pay_time,
                itemId: s.num_iid,
                price: s.price,
                orderId: s.oid,
                title: s.title,
                tId: i.tid,
                status: i.status
              })
            })
          }
        })
      }
    }
    console.log(`已支付的订单列表`, results)
    return results
  } catch (e) {
    console.log(`错误`, e)
    return []
  }
}
